// Configurable totals (replace with real data source later)
const totals = {
  papers: 128,
  categories: 3,
  tags: 42,
};

function countUp(el, to, duration = 1200) {
  const start = 0;
  const startTime = performance.now();
  const formatter = new Intl.NumberFormat('zh-CN');

  function tick(now) {
    const progress = Math.min(1, (now - startTime) / duration);
    const ease = 1 - Math.pow(1 - progress, 3); // easeOutCubic
    const current = Math.floor(start + (to - start) * ease);
    el.textContent = formatter.format(current);
    if (progress < 1) requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);
}

function initCounters() {
  const counters = document.querySelectorAll('.stat-number');
  const io = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const el = entry.target;
        const to = parseInt(el.getAttribute('data-count-to') || '0', 10);
        countUp(el, to);
        io.unobserve(el);
      }
    });
  }, { threshold: 0.4 });
  counters.forEach(el => io.observe(el));
}

function applyTotals() {
  const p = document.getElementById('stat-papers');
  const c = document.getElementById('stat-categories');
  const t = document.getElementById('stat-tags');
  if (p) p.setAttribute('data-count-to', String(totals.papers));
  if (c) c.setAttribute('data-count-to', String(totals.categories));
  if (t) t.setAttribute('data-count-to', String(totals.tags));
}

function initSmoothScroll() {
  document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', e => {
      const href = a.getAttribute('href');
      if (!href || href === '#') return;
      const target = document.querySelector(href);
      if (target) {
        e.preventDefault();
        const top = target.getBoundingClientRect().top + window.scrollY - 64; // header offset
        window.scrollTo({ top, behavior: 'smooth' });
      }
    });
  });
}

window.addEventListener('DOMContentLoaded', () => {
  applyTotals();
  initCounters();
  initSmoothScroll();
});
